<?php
/**
 * 广告类
 * User: Administrator
 * Date: 14-5-6
 * Time: 下午4:36
 */
class Advertise extends CI_Controller {
    function __construct() {
        parent::__construct ();
        $this->load->database ();
    }


    function advertise_list()
    {
        $this->load->view('advertise_list');
    }

    function add_advertise()
    {
        $this->load->view('add_advertise');
    }

    function addAdvertise()
    {
        $title      = $this->input->post('title');
        $start_time    = $this->input->post('start_time');
        $end_time  = $this->input->post('end_time');
        $id = (int)$this->input->post('id');

        if(!$id){
            $this->Madvertise->addAdvertise($title,$start_time,$end_time);
        }else{
            $this->Madvertise->editAdvertise($id,$title,$start_time,$end_time);
        }

        $arr = array();
        $arr ["ReturnCode"] = 1;
        echo json_encode($arr);
    }

    function loadAdvertise()
    {
        $title = $this->input->post('title');

        $query = $this->Madvertise->getAdvertise($title);

        $result = "";
        foreach ( $query as $row ) {
            $result .= "<tr>
					<td><input type='checkbox' value='" . $row->id . "' /></td>
							<td>$row->id</td>
							<td>$row->title</td>
							<td>$row->start_time</td>
							<td>$row->end_time</td>
							<td>
			<a href='javascript:void(0)' style='color:blue' onclick='modifyAdvertise(" . $row->id . ")'>编辑</a>
			&nbsp;&nbsp;&nbsp;&nbsp;
					<a href='javascript:void(0)' style='color:blue' onclick='delAdvertise(" . $row->id . ")'>删除</a>
							&nbsp;&nbsp;&nbsp;&nbsp;
					<a href='javascript:void(0)' style='color:blue' onclick='addAdvertisePic(" . $row->id . ")'>添加广告图片</a></td>";
            $result .= "</tr>";
        }
        echo $result;
    }

    function loadNewAdvertise()
    {
        $id = $this->input->post('id');

        if(!$id){
            $data['status'] = 1;
            $data['msg'] = '参数错误';
            echo json_encode($data);
            exit;
        }

        $data = $this->Madvertise->getAdvertiseById($id);
        echo json_encode($data);
    }

    function deleteAdvertise()
    {
        $ids = trim($this->input->post('ids'),',');


        $arr = array();
        if(empty($ids)){
            $arr ["ReturnCode"] = 2;
            echo json_encode($arr);
            exit;
        }

        $this->Madvertise->deleteAdvertise($ids);

        $arr ["ReturnCode"] = 1;
        echo json_encode($arr);
    }

    function add_Pic()
    {
        $this->load->view('add_pic');
    }

    function addPic()
    {
        $id = $this->input->post('id');
        $sort = $this->input->post('sort');
        $picpath = $this->input->post('picpath');
        $url = $this->input->post('url');

        $query = $this->Madvertisepic->addAdvertisePic($id,$picpath,$sort,$url);

        if($query){
            $arr ["ReturnCode"] = 1;
        }else{
            $arr ["ReturnCode"] = 2;
        }
        echo json_encode($arr);
    }

    function uploadImg($imgName) {
        $arr = array ();
        $arr ["ReturnCode"] = 0;
        // $picname = $_FILES ['mypic'] ['name'];
        // $picsize = $_FILES ['mypic'] ['size'];
        $picname = $_FILES ['Filedata'] ['name'];
        $picsize = $_FILES ['Filedata'] ['size'];
        if ($picname != "") {
            if ($picsize > 1024000 * 3) {
                $arr ["Msg"] = '图片大小不能超过3M';
                echo json_encode ( $arr );
                exit ();
            }
            $type = strstr ( $picname, '.' );
            if ($type != ".gif" && $type != ".jpg" && $type != ".png" && $type != ".jpeg") {
                $arr ["Msg"] = '图片格式不对！';
                echo json_encode ( $arr );
                exit ();
            }
            $rand = rand ( 100, 999 );
            $pics = "a" . "_" . date ( "YmdHis" ) . $rand . $type;
            // 上传路径
            $pic_path = "./uploadimg/";
            if (is_dir ( $pic_path ) == false) {
                mkdir ( $pic_path, 0777 );
            }
            $pic_path .= $pics;
            // move_uploaded_file ( $_FILES ['mypic'] ['tmp_name'], $pic_path );
            move_uploaded_file ( $_FILES [$imgName] ['tmp_name'], $pic_path );
        }
        $size = round ( $picsize / 1024, 2 );
        $arr = array (
            'ReturnCode' => 1,
            'name' => $picname,
            'src' => "uploadimg/" . $pics,
            'size' => $size
        );
        echo json_encode ( $arr );
    }

    function loadPic()
    {
        $id = $this->input->post('id');

        $query = $this->Madvertisepic->getAdvertisePic($id);

        $result = "";
        foreach ( $query as $row ) {
            $result .= '<tr><td>排序：</td><td style="vertical-align: middle; line-height: 130px; clear: both; width: 30px;padding:30px;">
            <input type="text" style="clear: both" value="'.$row->sort.'" name="sort[]"></td><td>url:</td><td><input type="text" value="'.$row->url.'" name="url" /></td><td style="text-align: left"><input type="hidden" value="'.$row->pic_path.'" name="picpath[]">
            <img style="width: 100px; height: 100px; vertical-align: middle; cursor: pointer" src="'.base_url().'/uploads/'.$row->pic_path.'">
            <input type="button" onclick="delButton(this)" value="删除" tyle="width: 80px"></td></tr>';
            $result .= "</tr>";
        }
        echo $result;
    }

    function emailsetting()
    {


       $this->load->view('emailsetting');
    }



    function addEmailsetting()
    {
        $smatHost = $this->input->post('smtp_host');
        $smatPort = $this->input->post('smtp_port');
        $smatUser = $this->input->post('smtp_user');
        $smatPass = $this->input->post('smtp_pass');
        $protocol = $this->input->post('smtp_protocol');
        $smtpEmail = $this->input->post('smtp_email');


        $smatPort = !empty($smatPort) ? $smatPort : '25';
        $protocol = !empty($protocol) ? $protocol : 'smtp';

        $config = array('smtp_host'=>$smatHost,'smtp_user'=>$smatUser,'smtp_pass'=>$smatPass,'smtp_protocol'=>$protocol,'smtp_port'=>$smatPort,'smtp_email'=>$smtpEmail);

        $return = $this->set_config($config,'email');

        if($return){
            $data = array('msg'=>'添加成功');
        }else{
            $data = array('msg'=>'添加失败');
        }
        echo json_encode($data);
    }

    function getEmailConfig()
    {
        $this->config->load('email',true,'','application');
        $email_config = $this->config->item('email');

        echo json_encode($email_config);
    }
    /**
     * 设置config文件
     * @param $config 配属信息
     * @param $filename 要配置的文件名称
     */
    function set_config($config, $filename="system") {
        $dir = dirname(__FILE__);
        $file =  $dir."/../../application/config/";
        $configfile = $file.$filename.'.php';
        if(!is_writable($configfile)) return 'Please chmod '.$configfile.' to 0777 !';
        $pattern = $replacement = array();
        foreach($config as $k=>$v) {
            if(in_array($k,array('smtp_host','smtp_user','smtp_pass','protocol','smtp_port'))) {
                $v = trim($v);
                $configs[$k] = $v;
                $pattern[$k] = "/'" .$k."'\s*=>\s*([']?)[^']*([']?)(\s*),/is";
                $replacement[$k] = "'".$k."' => \${1}".$v."\${2}\${3},";
            }
        }
        $str = file_get_contents($configfile);
        $str = preg_replace($pattern, $replacement, $str);
        return file_put_contents($configfile, $str, LOCK_EX);
    }

}
